package com.yvan.spring.autoconfig;

import com.yvan.Conv;
import com.yvan.platform.StringUtils;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Created by Administrator on 2018/9/12.
 */
public class EsAutoConfiguration {

    public static TransportClient client = null;
    @Value("${jzt.es.cluster-name:}")
    public String clusterName;
    @Value("${jzt.es.transport-address:}")
    public String transportAddress;

    @Bean
    public TransportClient transportClient() {

        if (StringUtils.isNullOrEmpty(transportAddress))
            return client;

        Settings settings;
        if (StringUtils.isNullOrEmpty(clusterName)) {
            settings = Settings.builder()
                    .put("client.transport.sniff", true)
                    .put("client.transport.ignore_cluster_name", true).build();
        } else {
            settings = Settings.builder()
                    .put("cluster.name", clusterName)
                    .put("client.transport.sniff", true)
                    .put("client.transport.ignore_cluster_name", false).build();
        }
        client = new PreBuiltTransportClient(settings);

        try {
            for (String addressInfo : transportAddress.split(",")) {
                String address = addressInfo.split(":")[0];
                int port = Conv.NI(addressInfo.split(":")[1]);
                client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(address), port));
            }
        } catch (UnknownHostException e) {
            System.out.println("Unknown Host:" + e.getStackTrace());
        }
        return client;
    }
}
